package com.complaint.rest.web;

import com.complaint.rest.model.User;
import com.complaint.rest.rc.RestClient;
import com.complaint.rest.security.util.SecurityUtil;
import com.complaint.rest.user.dto.RegistrationForm;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.validation.Valid;

/**
 * Created by Alex
 */
@Controller
@SessionAttributes("user")
public class RegistrationController {
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new RegistrationForm());
        return "registration";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String registerUserAccount(@Valid @ModelAttribute("user") RegistrationForm userAccountData,
                                      BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "registration";
        }

        User registered = RestClient.get().getUserByEmail(userAccountData.getEmail());

        if (registered != null) {
            model.addAttribute("error", "User with this e-mail already registered");
            return "registration";
        }

        registered = RestClient.get().addUser(new User(
                userAccountData.getFirstName(),
                userAccountData.getLastName(),
                userAccountData.getEmail(),
                userAccountData.getPassword()
        ));

        SecurityUtil.logInUser(registered);
        return "redirect:/";
    }
}
